package com.deyun.panelcabinet.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.FaceDetector;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.bifan.detectlib.FaceDetectTextureView;
import com.bifan.detectlib.FaceDetectView;
import com.deyun.panelcabinet.MainActivity;
import com.deyun.panelcabinet.R;
import com.deyun.panelcabinet.entity.FaceEntity;
import com.deyun.panelcabinet.utils.MyStringUtils;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends Activity {

    @BindView(R.id.btn_reg)
    Button btn_reg;
    @BindView(R.id.faceDetectView)
    FaceDetectView faceDetectView;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_id)
    EditText et_id;
    public Gson gson = new Gson();


    private boolean isSavingPic = false;
    private File imageFile;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    private class SavePicRunnable implements Runnable {
        Bitmap bitmap;

        SavePicRunnable(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        @Override
        public void run() {
            saveFacePicToLocal(bitmap);
            isSavingPic = false;
        }
    }

    // 测试用户id
    private int test_id = 6;

    // 是否注册的标识
    public boolean isReg = false;

    @OnClick({R.id.iv_back, R.id.btn_reg})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (faceDetectView != null) {
                    if (faceDetectView.isHasInit()) {
                        faceDetectView.stopCameraPreview();
                        faceDetectView.removeAllViews();
                        faceDetectView.release();
                        executorService.shutdown();
                    }
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                }
                finish();
                break;
            case R.id.btn_reg:
                if (isReg) {
                    // 开始执行录入逻辑
                    upLoadImage(imageFile);
                } else {
                    if (et_name.getText().toString().trim().isEmpty()) {
                        Toast.makeText(getApplicationContext(), "用户姓名不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (!MyStringUtils.isIDNumber(et_id.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), "请输入正确的身份证号码", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    btn_reg.setText("录入");
                    initFaceRecognitionParams();
                    isReg = true;
                }
                break;

        }
    }

    // 初始化人脸识别并开始启用
    public void initFaceRecognitionParams() {
        LogUtils.d("初始化人脸识别");
        faceDetectView.setVisibility(View.VISIBLE);
        if (!faceDetectView.isHasInit()) {
            //必须是在view可见后进行初始化
            faceDetectView.initView();
            faceDetectView.initCamera();
            faceDetectView.getDetectConfig().CameraType = Camera.CameraInfo.CAMERA_FACING_FRONT;
            faceDetectView.getDetectConfig().EnableFaceDetect = true;
            faceDetectView.getDetectConfig().MinDetectTime = 3000;
            faceDetectView.getDetectConfig().Simple = 1.0f;//图片检测时的压缩取样率，0~1，越小检测越流畅
            faceDetectView.getDetectConfig().MaxDetectTime = 5000;//进入智能休眠检测，以2秒一次的这个速度检测
            faceDetectView.getDetectConfig().EnableIdleSleepOption = false;//不启用智能休眠检测机制
            faceDetectView.getDetectConfig().IdleSleepOptionJudgeTime = 1000 * 10;//1分钟内没有检测到人脸，进入智能休眠检测
        }
        faceDetectView.startCameraPreview();
    }

    // 保存人脸图片到本地
    private void saveFacePicToLocal(Bitmap bitmap) {
        LogUtils.d("检测到人脸，图片正在保存到本地");
        // 安卓10的适配 沙盒模式
        if (android.os.Build.VERSION.SDK_INT >= 30) {
            try {
                // 沙盒下的目录名
                String signImage = "temp";
                // 沙盒下的图片名
                String fileName = "face.jpg";
                File PICTURES = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                // 沙盒下的目录
                File imageFileDirectory = new File(PICTURES + "/" + signImage);
                if (imageFileDirectory.exists()) {
                    imageFile = new File(PICTURES + "/" + signImage + "/" + fileName);
                    FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    bitmap.recycle();
                } else if (imageFileDirectory.mkdir()) {//如果该文件夹不存在，则新建
                    imageFile = new File(PICTURES + "/" + signImage + "/" + fileName);
                    FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    bitmap.recycle();
                }
            } catch (Exception e) {
                LogUtils.d("安卓10保存图片失败信息 " + e.toString());
            }
        } else {
            String picPath = Environment.getExternalStorageDirectory() + "/face.jpg";
            FileOutputStream fileOutputStream = null;
            imageFile = new File(picPath);
            try {
                imageFile.createNewFile();
            } catch (IOException e) {
                LogUtils.d("保存失败" + e.toString() + "," + picPath);
                e.printStackTrace();
            }
            try {
                fileOutputStream = new FileOutputStream(imageFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (fileOutputStream != null) {
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            bitmap.recycle();
        }
    }

    // 上传图片到服务器进行比对
    public void upLoadImage(File file) {
        if (file != null) {
            String url_test = "http://10.1.20.95:9000/register_face/" + test_id;
            RequestParams params = new RequestParams(url_test);
            params.setCacheMaxAge(0);
            params.setMultipart(true);
            params.addBodyParameter("file", file, "multipart/form-data");
            LogUtils.d("upload_url = " + params.getUri());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LogUtils.d("result = " + result);
                    try {
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
                        boolean face_found = (boolean) jsonObject.get("face_found");
                        int code = (int) jsonObject.get("code");
                        String msg = jsonObject.getString("msg");
                        if (face_found && code == 100) {
                            Toast.makeText(getApplicationContext(), "人脸信息录入成功", Toast.LENGTH_SHORT).show();
                            if (faceDetectView != null) {
                                if (faceDetectView.isHasInit()) {
                                    faceDetectView.stopCameraPreview();
                                    faceDetectView.removeAllViews();
                                    faceDetectView.release();
                                    executorService.shutdown();
                                }
                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                            }
                            finish();
                        } else {
                            if (msg != null) {
                                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                    LogUtils.d("onError = " + ex.getMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            LogUtils.d("file = null");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);


        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        faceDetectView.setFramePreViewListener(new FaceDetectTextureView.IFramePreViewListener() {
            @Override
            public boolean onFrame(Bitmap preFrame) {
                //每一帧回调
                //这个这帧preFrame处理了就是进行了回收，返回true
                //否则返回false，内部进行回收处理
                return false;
            }

            @Override
            public boolean onFaceFrame(Bitmap preFrame, FaceDetector.Face[] faces) {
                //faces是检测出来的人脸参数
                //检测到人脸的回调,保存人脸图片到本地
                if (isSavingPic == false) {
                    isSavingPic = true;
                    executorService.submit(new RegisterActivity.SavePicRunnable(preFrame));
//                    if (faces.length != 0) {
//                        LogUtils.d("是否可信参数" + faces[0].confidence());
//                        LogUtils.d("双眼距离" + faces[0].eyesDistance());
//                    }
                }
                //这个这帧preFrame处理了就是进行了回收，返回true
                //否则返回false，内部进行回收处理
                return true;
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        hideSystemNavigationBar();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (faceDetectView != null) {
//            faceDetectView.release();
//        }
    }

    // 隐藏底部和顶部状态栏
    private void hideSystemNavigationBar() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = this.getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    // 屏蔽home和返回
    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;

    @Override
    public void onAttachedToWindow() {
        this.getWindow().addFlags(FLAG_HOMEKEY_DISPATCHED);
        super.onAttachedToWindow();
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
    }
}